cmake_minimum_required(VERSION 3.20)

cmake_policy(SET CMP0123 NEW)

set(CMAKE_SYSTEM_NAME Generic)
set(CPU_CORE cortex-m3)
set(CMAKE_SYSTEM_PROCESSOR ${CPU_CORE})

set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_LIST_DIR}/toolchain.cmake)

project(LED C ASM)

string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE_UPPER)
if(${BUILD_TYPE_UPPER} STREQUAL "RELEASE")
    add_compile_options(-Os)
else()
    add_compile_options(-Og -g)
endif()

add_compile_definitions(STM32F10X_MD)
add_compile_definitions(USE_STDPERIPH_DRIVER)

include_directories(
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/BSP/
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/CMSIS/Core/
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/CMSIS/Device/ST/STM32F10x/Include/
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/STM32F10x_StdPeriph_Driver/inc/
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/SYS/
    ${CMAKE_CURRENT_LIST_DIR}/User/
)

file(GLOB SOURCE_FILE
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/BSP/led/*.c
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/CMSIS/Core/*.c
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/CMSIS/Device/ST/STM32F10x/Source/Templates/*.c
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/STM32F10x_StdPeriph_Driver/src/*.c
    ${CMAKE_CURRENT_LIST_DIR}/Drivers/SYS/*.c
    ${CMAKE_CURRENT_LIST_DIR}/User/*.c
)

set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/output)
set(HEX_FILE ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}.hex)
set(BIN_FILE ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}.bin)
set(MAP_FILE ${EXECUTABLE_OUTPUT_PATH}/${PROJECT_NAME}.map)

if(USE_ARMGCC)
    SET(STARTUP_FILE ${CMAKE_CURRENT_LIST_DIR}/startup_stm32f10x_md.s)
    SET(LINKER_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/STM32F103C8TX_FLASH.ld)

    add_compile_options(
        -mcpu=${CPU_CORE}
        -mthumb
        -mthumb-interwork
        -ffunction-sections
        -fdata-sections
        -fno-common
        -fmessage-length=0
    )

    add_link_options(
        -Wl,-Map=${MAP_FILE}
        -Wl,--print-memory-usage
        -Wl,--gc-sections
        -T ${LINKER_SCRIPT}
    )
endif()

add_executable(${PROJECT_NAME} ${SOURCE_FILE} ${STARTUP_FILE})
set_target_properties(${PROJECT_NAME} PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}
)

if(USE_ARMGCC)
    add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -Oihex $<TARGET_FILE:${PROJECT_NAME}> ${HEX_FILE}
        COMMAND ${CMAKE_OBJCOPY} -Obinary $<TARGET_FILE:${PROJECT_NAME}> ${BIN_FILE}
        COMMAND ${CMAKE_SIEZE} $<TARGET_FILE:${PROJECT_NAME}>
    )
endif()
